package com.dy.yunying.biz.controller.hongbao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.dto.hongbao.HbInvitationTopDto;
import com.dy.yunying.api.entity.GameRole;
import com.dy.yunying.api.entity.hongbao.HbActivityRoleInfo;
import com.dy.yunying.api.entity.hongbao.HbInvitationTop;
import com.dy.yunying.api.vo.hongbao.InvitationTopVo;
import com.dy.yunying.biz.service.hongbao.HbActivityRoleInfoService;
import com.dy.yunying.biz.service.hongbao.HbInvitationTopService;
import com.dy.yunying.biz.service.manage.GameRoleService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.CommonUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 手动榜单表
 * @author  chengang
 * @version  2021-10-27 19:21:20
 * table: hb_invitation_top
 */
@RestController
@RequestMapping("/invitation")
@RequiredArgsConstructor
public class HbInvitationTopController {
	
    private final HbInvitationTopService hbInvitationTopService;
	private final GameRoleService gameRoleService;
	private final HbActivityRoleInfoService hbActivityRoleInfoService;

	@Value("${invitation.top:10}")
	private Integer top;

	@SysLog("新增或编辑手动排行榜")
	@PostMapping("/saveOrUpdate")
	public R saveOrUpdate(@RequestBody HbInvitationTopDto dto) {
		R check = this.baseCheck(dto);
		if (check.getCode() == CommonConstants.FAIL) {
			return check;
		}
		//校验角色名称不能重复,不同的活动之间可以重复
		List<HbInvitationTop> list = hbInvitationTopService.list(Wrappers.<HbInvitationTop>lambdaQuery()
				.eq(HbInvitationTop::getActivityId,dto.getActivityId())
				.eq(HbInvitationTop::getDeleted,0)
				.and(wrapper -> wrapper.eq(HbInvitationTop::getNickName,dto.getNickName()))
				.and(dto.getId() != null,wrapper -> wrapper.ne(HbInvitationTop::getId,dto.getId())));
		if (CollectionUtils.isNotEmpty(list)) {
			return R.failed("角色名称不能重复");
		}
		HbInvitationTop entity = new HbInvitationTop();
		entity.setId(dto.getId());
		entity.setActivityId(dto.getActivityId());
		entity.setNickName(dto.getNickName());
		entity.setSettingMoney(new BigDecimal(dto.getSettingMoney()));
		PigUser user = SecurityUtils.getUser();
		entity.setCreateId(user.getId().longValue());
		entity.setUpdateId(user.getId().longValue());
		return R.ok(hbInvitationTopService.saveOrUpdate(entity));
	}

	@SysLog("删除手动排行榜")
	@GetMapping("/delete")
	public R delete(@RequestParam Long id) {
		if (id == null) {
			return R.failed("主键ID不能为空");
		}
		PigUser user = SecurityUtils.getUser();
		return R.ok(hbInvitationTopService.update(Wrappers.<HbInvitationTop>lambdaUpdate()
				.eq(HbInvitationTop::getDeleted,0)
				.eq(HbInvitationTop::getId,id)
				.set(HbInvitationTop::getDeleted,1)
				.set(HbInvitationTop::getUpdateId,user.getId())));
	}

	@PreAuthorize("@pms.hasPermission('ACTIVITY_INVITATION_TOP')")
	@GetMapping("/list")
	public R getList(HbInvitationTopDto dto) {
		if (dto.getActivityId() == null) {
			return R.failed("活动ID不能为空");
		}
		return R.ok(this.getManualTop(dto.getActivityId()));
	}

	private List<HbInvitationTop> getManualTop(Long activityId){
		LambdaQueryWrapper<HbInvitationTop> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(HbInvitationTop::getDeleted, 0));
		query.and(wrapper -> wrapper.eq(HbInvitationTop::getActivityId, activityId));
		query.orderByAsc(HbInvitationTop::getCreateTime);
		return hbInvitationTopService.list(query);
	}

	@GetMapping("/preview")
	public R preview(HbInvitationTopDto dto) {
		if (dto.getActivityId() == null) {
			return R.failed("活动ID不能为空");
		}
		//有用户ID和角色ID的表示非手动设置的
		List<InvitationTopVo> result = new ArrayList<>();
		//获取活动对应的榜单
		LambdaQueryWrapper<HbActivityRoleInfo> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(HbActivityRoleInfo::getDeleted, 0));
		query.and(wrapper -> wrapper.eq(HbActivityRoleInfo::getActivityId, dto.getActivityId()));
		query.orderByDesc(HbActivityRoleInfo::getTotalIncome);
		query.last("limit " + top);
		List<HbActivityRoleInfo> topList = hbActivityRoleInfoService.list(query);

		if (CollectionUtils.isNotEmpty(topList)) {
			//获取角色ID集合，存在同一个角色充值多笔故需要去重
			List<String> roleIds = topList.stream().map(HbActivityRoleInfo::getRoleId).distinct().collect(Collectors.toList());
			//角色名称取(pig.game_role)\备选表(maindb.wan_user_game_roles)
			List<GameRole> roles = gameRoleService.list(Wrappers.<GameRole>lambdaQuery().in(GameRole::getRoleId,roleIds));
			//角色ID有重复
//			Map<String,GameRole> roleMap = roles.stream().collect(Collectors.toMap(GameRole::getRoleId, Function.identity()));
			Map<String,List<GameRole>> roleMap = roles.stream().collect(Collectors.groupingBy(GameRole::getRoleId));
			topList.forEach(top -> {
				List<GameRole> roleVoList = roleMap.get(top.getRoleId());
				String roleName = "";
				if (CollectionUtils.isNotEmpty(roleVoList)) {
					List<GameRole> filterList = roleVoList.stream()
							.filter(v -> v.getUserId().equals(top.getUserId())
									&& v.getPgameId().equals(top.getPgameId())
									&& v.getAreaId().equals(top.getAreaId())
									&& v.getRoleId().equals(top.getRoleId()))
							.collect(Collectors.toList());
					roleName = CollectionUtils.isEmpty(filterList) ? "" : filterList.get(0).getRoleName();
				}
				InvitationTopVo topVo = new InvitationTopVo(top.getActivityId(),
						top.getUserId(),top.getRoleId(),roleName,top.getTotalIncome());
				result.add(topVo);
			});
		}

		//获取手动榜单
		List<HbInvitationTop> manualTopList = this.getManualTop(dto.getActivityId());

		if (CollectionUtils.isNotEmpty(manualTopList)) {
			//按金额倒叙，不区分角色名称
			manualTopList.forEach(manualTop -> {
				InvitationTopVo topVo = new InvitationTopVo(manualTop.getActivityId(),
						null,null,manualTop.getNickName(),manualTop.getSettingMoney());
				result.add(topVo);
			});
		}

		//金额倒叙取前10
		return R.ok(result.stream()
				.sorted(Comparator.comparing(InvitationTopVo::getTotalIncome).reversed())
				.filter(v -> v.getTotalIncome().compareTo(new BigDecimal(0)) > 0)
				.limit(top.longValue())
				.collect(Collectors.toList()));
	}

	private R baseCheck(HbInvitationTopDto dto){
		if(dto.getActivityId() == null) {
			return R.failed("活动ID不能为空");
		}

		if (StringUtils.isBlank(dto.getNickName())) {
			return R.failed("角色名称不能为空");
		}

		if (dto.getNickName().length() > 6) {
			return R.failed("角色名称长度不能超过6");
		}

		if (StringUtils.isBlank(dto.getSettingMoney())) {
			return R.failed("金额不能为空");
		}

		if (!CommonUtils.isMoney(dto.getSettingMoney(),0)) {
			return R.failed("金额格式不正确");
		}

		if (dto.getSettingMoney().length() > 7) {
			return R.failed("金额长度不能超过7位");
		}

		return R.ok();

	}


}


